package com.security.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.security.config.JwtConfig;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JwtToken生成的工具类
 * Created by zn on 2018/4/26.
 */
@Slf4j
public class JwtTokenUtil {

    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_CREATED = "created";

    // 加载配置文件
    private final JwtConfig jwtConfig = SpringUtil.getBean(JwtConfig.class);

    /**
     * 根据用户信息生成token
     */
    public String createJWTToken(UserDetails userDetails, String ip) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims, ip);
    }

    /**
     * 根据负责生成JWT的token
     */
    private String generateToken(Map<String, Object> claims, String ip) {
        if (StringUtils.isEmpty(ip)) return null;
        //生成秘钥
        SecretKey secretKey = generalKey(ip);
        JwtBuilder builder = Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, secretKey);
        return builder.compact();
    }

    /**
     * 从token中获取JWT中的负载
     */
    private Claims getClaimsFromToken(String token, String ip) {
        if (StringUtils.isEmpty(ip)) return null;
        Claims claims = null;
        try {
            SecretKey secretKey = generalKey(ip);
            claims = Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.info("JWT格式验证失败:{}", token);
        }
        return claims;
    }

    /**
     * 生成token的过期时间
     */
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + jwtConfig.getExpiration() * 1000);
    }

    /**
     * 从token中获取登录用户名
     */
    public String getUserNameFromToken(String token, String ip) {
        if (StringUtils.isEmpty(ip)) return null;
        String username;
        try {
            Claims claims = getClaimsFromToken(token, ip);
            if (claims == null || claims.getSubject() == null) return null;
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    /**
     * 验证token是否还有效
     *
     * @param token       客户端传入的token
     * @param userDetails 从数据库中查询出来的用户信息
     */
    public boolean validateToken(String token, UserDetails userDetails, String ip) {
        if (StringUtils.isEmpty(token) || StringUtils.isEmpty(ip)) return false;
        String username = getUserNameFromToken(token, ip);
        return username.equals(userDetails.getUsername()) && !isTokenExpired(token, ip);
    }

    /**
     * 判断token是否已经失效
     */
    private boolean isTokenExpired(String token, String ip) {
        if (StringUtils.isEmpty(token)) return false;
        if (StringUtils.isEmpty(ip)) return false;
        Date expiredDate = getExpiredDateFromToken(token, ip);
        if (expiredDate == null) return false;
        return expiredDate.before(new Date());
    }

    /**
     * 从token中获取过期时间
     */
    private Date getExpiredDateFromToken(String token, String ip) {
        if (StringUtils.isEmpty(token)) return null;
        if (StringUtils.isEmpty(ip)) return null;
        Claims claims = getClaimsFromToken(token, ip);
        if (claims == null) return null;
        return claims.getExpiration();
    }


    /**
     * 当原来的token没过期时是可以刷新的
     *
     * @param oldToken 带tokenHead的token
     */
    public String refreshHeadToken(String oldToken, String ip) {
        if (StrUtil.isEmpty(oldToken) || StringUtils.isEmpty(ip)) return null;
        String token = null;
        if (oldToken.startsWith("bearer ") || oldToken.startsWith("Bearer ")) {
            token = oldToken.substring(7);
        }
        if (StrUtil.isEmpty(token)) {
            return null;
        }
        //token校验不通过
        Claims claims = getClaimsFromToken(token, ip);
        if (claims == null) {
            return null;
        }
        //如果token已经过期，不支持刷新
        if (isTokenExpired(token, ip)) {
            return null;
        }
        //如果token在30分钟之内刚刷新过，返回原token
        if (tokenRefreshJustBefore(token, ip)) {
            return token;
        } else {
            claims.put(CLAIM_KEY_CREATED, new Date());
            return generateToken(claims, ip);
        }
    }


    /**
     * 判断token在指定时间内是否刚刚刷新过
     *
     * @param token 原token
     */
    private boolean tokenRefreshJustBefore(String token, String ip) {
        if (StringUtils.isEmpty(token) || StringUtils.isEmpty(ip)) return false;
        Claims claims = getClaimsFromToken(token, ip);
        if (claims == null) return false;
        Date created = claims.get(CLAIM_KEY_CREATED, Date.class);
        Date refreshDate = new Date();
        //刷新时间在创建时间的指定时间内
        return refreshDate.after(created) && refreshDate.before(DateUtil.offsetSecond(created, 1800));
    }

    /**
     * 生成加密 secretKey
     */
    public SecretKey generalKey(String ip) {
        if (StringUtils.isEmpty(ip)) return null;
        String key = String.format("%s_%s", ip, jwtConfig.getSecret());
        byte[] encodedKey = Base64.getEncoder().encode(key.getBytes());
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    }

}
